package com.javen.demo;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * CountDownLatch 减
 * CyclicBarrier 增
 */
@Slf4j
public class CyclicBarrierDemo {

    public static void semaphore(){

        Semaphore semaphore = new Semaphore(3)  ;
        for (int i = 0; i < 10; i++) {
             new Thread(() -> {
                 try {
                     semaphore.acquire();
                     log.info("{} 抢到车位",Thread.currentThread().getName());
                     TimeUnit.SECONDS.sleep(3);
                     log.info("{} 停车3秒后离开",Thread.currentThread().getName());
                 } catch (InterruptedException e) {
                     e.printStackTrace();
                 }finally {
                     semaphore.release();
                 }
             },String.valueOf(i)).start();
        }
    }

    public static void cyclicBarrier() {
        int count = 6;
        final CyclicBarrier cyclicBarrier = new CyclicBarrier(count, () -> log.info("人到齐了，可以开会啦..."));
        for (int i = 0; i < count; i++) {
            new Thread(() -> {
                log.info("{} 加入会议室", Thread.currentThread().getName());
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }, String.valueOf(i)).start();
        }
    }

    public static void countDownLatch() {
        int count = 6;
        final CountDownLatch cdl = new CountDownLatch(count);
        try {

            for (int i = 0; i < 6; i++) {
                new Thread(() -> {
                    cdl.countDown();
                    log.info("{} come in ", Thread.currentThread().getName());
                }, String.valueOf(i)).start();
            }

            log.info("{} 等待中...", Thread.currentThread().getName());
            cdl.await();
            log.info("可以继续了....");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }

    public static void main(String[] args) {
        cyclicBarrier();
        log.info("=============");
        countDownLatch();
        log.info("=============");
        semaphore();
    }
}
